import React, { Component } from "react";
import { connect } from "dva";

import { Form, Input, Button, Menu, Icon, message, Modal, Select } from "antd";
import "./less/role.less";
import PTable from "../../../components/Pro/PTable";
import NewRole from "./NewRole";
import UpdateRole from "./UpdateRole";
import UpdateRoleGroup from "./UpdateRoleGroup";
import RoleAllow from "./RoleAllow";
import NewRoleGroup from "./NewRoleGroup";
import {
  searchRoleAndRoleGroupList, //查询角色组与角色列表功能
  batchesDelete, //批量删除角色中人员功能
  systemComRoleInsertPerRole //批量添加角色中人员功能
} from "../../../services/api";
import PartmentButton from "../../../components/PartmentButton";

const { Search } = Input;
const { SubMenu } = Menu;
const { Option } = Select;
const { confirm } = Modal;

// const { Option } = Select;
// const { MenuItemGroup } = Menu;

@connect(state => ({
  profile: state.profile
}))
@Form.create()

/**
 * 部门管理组件
 */
export default class Role extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      chargePerVisible: false,
      /**
       * 各个抽屉
       */
      roleOpen: false,
      updateRoleOpen: false,
      roleGroupOpen: false,
      updateroleGroupOpen: false,
      roleAllowOpen: false,
      /**
       * 抽屉需要
       */
      selectedRowIds: [], //需要删除的信息id值集合
      selectedRowKeys: [],
      roleGroupList: [],
      /**
       * 删除模态框
       */
      ModalText: "请先移除当前部门下的人员，再删除当前角色！",
      visible: false,
      confirmLoading: false,
      /**
       * 批量离职删除模态框
       */
      BulkDeparturesModalText:
        "XXX（手机号）离职后将取消关联的任务及审批流程。是否确定离职处理？",
      bulkDeparturesVisible: false,
      bulkDeparturesConfirmLoading: false,
      // company: '百川信（厦门）网络服务信息有限公司',
      placeholder: "请输入内容",
      // openKeys: ['a1'],
      forceUpdate: false,
      roleGroupSequence: "", //菜单组序列
      roleGroupdefault: [],
      edit: {
        roleId: "",
        roleGroupId: ""
      },
      pageParm: {
        pageSize: "10",
        pageNumber: "1",
        roleId: ""
        // comId: "",
      },
      roleGroupData: [
        {
          roleGroupName: "",
          roleGroupId: "",
          comRolesList: [
            {
              roleName: "",
              roleId: "",
              personCount: "",
              sid: ""
            }
          ]
        }
      ],
      caption: "",
      personCount: ""
    };
  }

  //批量添加角色中人员功能
  systemComRoleInsertPerRole = () => {
    systemComRoleInsertPerRole({
      perIds: JSON.stringify(this.state.chargePerIdStr),
      roleId: this.state.roleId
    })
      .then(res => {
        console.log(res, "批量添加角色中人员功能-res1");
        this.refs.PTable.ajaxRequest();
      })
      .catch(err => {
        console.log(err, "批量添加角色中人员功能-err");
      });
  };

  //宣染人员选择器
  renderUserSelect = () => {
    /* 考勤组负责人: */
    return (
      <PartmentButton
        onCheck={(chargePerIdStr, chargePerIdList) => {
          const checkedkey = chargePerIdList.map(val => val.key);
          this.setState(
            {
              chargePerVisible: false,
              chargePerIdStr: checkedkey
            },
            () => {
              this.systemComRoleInsertPerRole();
            }
          );
        }}
        handleCancel={() => {
          this.setState({
            chargePerVisible: false,
            chargePerIdStr: []
          });
        }}
        value={this.state.chargePerIdStr}
        visible={this.state.chargePerVisible} //{this.state.chargePerVisible}
      />
    );
  };

  componentWillMount = () => {};
  componentDidMount() {
    this.getSearchRoleAndRoleGroupList();
  }

  onSelect = (selectedKeys, info) => {
    console.log("onSelect", info);
  };

  getSearchRoleAndRoleGroupList = () => {
    searchRoleAndRoleGroupList({}).then(data => {
      console.log("getRoleList-初始化菜单", data.data);
      if (data) {
        this.setState({
          roleGroupData: data.data,
          personCount: this.state.roleGroupData[0].comRolesList[0].personCount,
          caption: this.state.roleGroupData[0].comRolesList[0].roleName
        });
        const pageParm = { ...this.state.pageParm };
        pageParm.roleId = this.state.roleGroupData[0].comRolesList[0].roleId;
        const roleGroupdefault1 = this.state.roleGroupdefault;
        roleGroupdefault1.push(
          this.state.roleGroupData[0].roleGroupId.toString()
        );
        console.log("菜单的第一个组key", roleGroupdefault1);
        this.setState({
          pageParm,
          caption: this.state.roleGroupData[0].comRolesList[0].roleName,
          roleGroupdefault: roleGroupdefault1,
          personCount: this.state.roleGroupData[0].comRolesList[0].personCount
        });
      }
    });
  };

  getEnterpriseRoleGroupGet = () => {
    // console.log("getComId:", comId);
    searchRoleAndRoleGroupList().then(data => {
      console.log("getRoleList", data.data);
      if (data) {
        this.setState({
          roleGroupList: data.data
        });
      }
    });
  };
  // 批量删除
  handleDeleteList = () => {
    const that = this;
    const keyNumber = this.state.selectedRowIds.length;
    const keyId = this.state.selectedRowIds;
    console.log("id集合" + keyId);
    if (keyNumber <= 0) {
      message.warning("请选择需要删除的信息！");
    } else {
      console.log(this.state.selectedRowIds);
      confirm({
        title: "是否删除所选方案，删除后方案不可找回。是否确认删除？",
        okText: "确认",
        cancelText: "取消",
        onOk() {
          that.comJobDelete(keyId);
        },
        onCancel() {
          console.log("Cancel");
        }
      });
    }
  };

  // 订单删除
  comJobDelete = perIds => {
    console.log("perIds", perIds);
    batchesDelete({ perIds, roleId: this.state.pageParm.roleId }).then(
      data => {
        console.log("角色人员删除", data);
        this.setState({
          selectedRowIds: [],
          selectedRowKeys: []
        });
        message.info("角色人员删除成功！");
        // this.resetting();
      },
      err => {
        console.log("角色人员删除失败", err);
        message.warning("角色人员删除失败！" + err);
      }
    );
  };
  // rootSubmenuKeys = ['a1', 'a2', 'a3'];

  /**
   * 删除模态框
   */
  showModal = () => {
    this.setState({
      visible: true
    });
  };
  roleMenuClick = e => {
    const pageParm = { ...this.state.pageParm };
    console.log("ClickedroleMenu", e);
    console.log("角色组Id-roleGroupId:", e.keyPath[1]);
    console.log("角色Id-roleId:", e.key);
    // console.log('value:', e.key, ",", e.item.props.title);
    // console.log('第一位:', ['{this.state.roleGroupData[0].roleGroupId}'], ",", [this.state.roleGroupData[0].comRolesList[0].roleId]);

    pageParm.roleId = e.key;
    this.setState({
      roleId: e.key,
      pageParm,
      roleGroupSequence:
        e.keyPath[1] !== this.state.roleGroupData[0].roleGroupId
          ? e.keyPath[1]
          : "",
      caption: e.item.props.title,
      personCount: e.item.props.personCount
    });
  };
  handleOk = () => {
    this.setState({
      ModalText: "请先移除当前部门下的人员，再删除当前部门！",
      confirmLoading: true
    });
    setTimeout(() => {
      this.setState({
        visible: false,
        confirmLoading: false
      });
    }, 2000);
  };
  handleCancel = () => {
    console.log("Clicked cancel button");
    this.setState({
      visible: false
    });
  };

  /**
   * 批量离职删除模态框
   */
  showBulkDeparturesModal = () => {
    this.setState({
      bulkDeparturesVisible: true
    });
  };
  handleBulkDeparturesOk = () => {
    this.setState({
      BulkDeparturesModalText:
        "XXX（手机号）离职后将取消关联的任务及审批流程。是否确定离职处理？",
      confirmLoading: true
    });
    setTimeout(() => {
      this.setState({
        bulkDeparturesVisible: false,
        confirmLoading: false
      });
    }, 2000);
  };
  handleBulkDeparturesCancel = () => {
    console.log("Clicked cancel button");
    this.setState({
      bulkDeparturesVisible: false
    });
  };

  handleHeart = item => {
    console.log(item);
  };

  // 下级角色组别
  handleList = () => {
    const listName = this.state.caption;
    const ertContent = [];
    this.state.roleGroupData.forEach(val => {
      if (val.roleGroupName === listName) {
        if (val.comRolesList.length !== 0) {
          val.comRolesList.forEach(text => {
            console.log(text.roleName);
            return ertContent.push(
              <li key={text.roleId}>
                <a href="#">
                  {text.roleName}
                  <Icon type="right" />
                </a>
              </li>
            );
          });
        } else {
          ertContent.push("");
        }
      }
    });
    return ertContent;
  };
  //新增角色抽屉
  openNewRoleDrawer = open => {
    console.log("新增角色开关：", open);
    this.setState({ roleOpen: open });
    this.refs.wed.getEnterpriseRoleGroupGet();
  };

  //编辑角色
  openUpdateRoleDrawer = (open, roleId) => {
    const edit = { ...this.state.edit };
    edit.roleId = roleId;
    // console.log("修改角色开关：", open, "，当前roleId：", roleId);
    this.setState({ updateRoleOpen: open, edit });
  };

  //权限设置
  openRoleAllowDrawer = (open, roleId) => {
    const edit = { ...this.state.edit };
    edit.roleId = roleId;
    // console.log("修改角色权限开关：", open, "，roleId的：", roleId);
    this.setState({ roleAllowOpen: open, edit });
  };

  //新增角色组抽屉
  openNewRoleGroupDrawer = open => {
    // console.log("新增角色组开关：", open);
    this.setState({ roleGroupOpen: open });
  };

  //编辑角色组抽屉
  openUpdateNewRoleGroupDrawer = (open, roleGroupId) => {
    const edit = { ...this.state.edit };
    edit.roleGroupId = roleGroupId;
    // console.log("修改角色组开关：", open, "，roleGroupId的：", roleGroupId);
    this.setState({ updateroleGroupOpen: open, edit });
  };

  renderRoleGroup = () => {
    return this.state.roleGroupList.map((val, key) => {
      return (
        <Option key={key} value={val.roleGroupId + ""}>
          {val.roleGroupName}
        </Option>
      );
    });
  };

  // 角色及角色组菜单
  renderCourse = () => {
    console.log(
      "this.state.roleGroupData-权限，，，，，",
      this.state.roleGroupData
    );
    const arrs = this.state.roleGroupData.map((val, item) => {
      // if (val.comRolesList.length !== 0) {
      return (
        <SubMenu
          key={val.roleGroupId}
          title={
            <span
              style={{
                display: "inline-block",
                width: "130px",
                overflow: "hidden",
                textOverflow: "ellipsis",
                whiteSpace: "nowrap"
              }}
            >
              <Icon
                type="folder-open"
                style={{ fontSize: 14, color: "#909CA8" }}
              />
              <span> {val.roleGroupName}</span>
              {val.roleGroupId !== this.state.roleGroupData[0].roleGroupId ? (
                <span
                  style={{ position: "absolute", right: "30px" }}
                  onClick={this.openUpdateNewRoleGroupDrawer.bind(
                    this,
                    true,
                    val.roleGroupId
                  )}
                >
                  <Icon
                    type="edit"
                    style={{ fontSize: 14, color: "#909CA8" }}
                  />
                </span>
              ) : (
                ""
              )}
            </span>
          }
        >
          {val.comRolesList.map(name => {
            return (
              <Menu.Item
                key={name.roleId}
                title={name.roleName}
                personCount={name.personCount}
              >
                <Icon type="user" style={{ fontSize: 14, color: "#909CA8" }} />
                {name.roleName}
              </Menu.Item>
            );
          })}
        </SubMenu>
      );
      // } else {
      //   return (<Menu.Item key={val.roleGroupId}>
      //     <Icon type="folder-open" style={{ fontSize: 14, color: '#909CA8' }} />
      //     {val.roleGroupName}
      //   </Menu.Item>);
      // }
    });
    return arrs;
  };

  renderColums = () => {
    const selectedRowKey = this.state.selectedRowKeys;
    const rowSelection = {
      selectedRowKeys: selectedRowKey,
      onChange: selectedRowKeys => {
        this.setState({
          selectedRowKeys
        });
      },
      onSelect: (record, selected) => {
        const selectId = this.state.selectedRowIds;
        if (selected === true) {
          selectId.push(record.perId);
        } else {
          for (let i = 0; i < selectId.length; i++) {
            if (selectId[i] === record.perId) {
              selectId.splice(i, 1);
              break;
            }
          }
        }
        this.setState({
          selectedRowIds: selectId
        });
      },
      onSelectAll: (selected, selectedRows) => {
        let selectId = [];
        if (selected === true) {
          for (let i = 0; i < selectedRows.length; i++) {
            selectId.push(selectedRows[i].perId);
          }
        } else {
          selectId = [];
          // selectedRowKeys:selectedRowKey
        }
        this.setState({
          selectedRowIds: selectId
        });
      }
    };

    const columns = [
      {
        title: "姓名",
        dataIndex: "name",
        key: "name"
      },
      {
        title: "部门",
        dataIndex: "departName",
        key: "departName"
      },
      {
        title: "手机号",
        dataIndex: "mobilePhone",
        key: "mobilePhone"
      }
    ];
    return (
      <PTable
        ref="PTable"
        style={{ marginTop: 20 }}
        columns={columns}
        url="searchPerSonByRoleId"
        pageParm={this.state.pageParm}
        rowSelection={rowSelection}
        forceUpdate={this.state.forceUpdate}
        showTotal={total => `共搜素到${total}条记录`}
      />
    );
  };

  updateRoleGroupSequence = () => {
    this.setState({
      roleGroupSequence: "" //菜单组序列
    });
  };

  render() {
    /**
     * 删除模态框
     */
    const {
      visible,
      confirmLoading,
      ModalText,
      bulkDeparturesVisible,
      bulkDeparturesConfirmLoading,
      BulkDeparturesModalText
    } = this.state;

    return (
      <div className="Role">
        <div className="department-content">
          <div className="department-inquiry">
            <Search
              size="large"
              placeholder={this.state.placeholder}
              style={{ width: 200, display: "none" }}
              onSearch={value => console.log(value)}
              maxLength="20"
            />
            <div className="depart-button">
              <Button onClick={this.openNewRoleGroupDrawer.bind(this, true)}>
                新增角色组
              </Button>
              <Button
                onClick={this.openNewRoleDrawer.bind(this, true)}
                className="button-right"
              >
                新增角色
              </Button>
            </div>
            <div className="depart-menu">
              <Menu
                mode="inline"
                // defaultSelectedKeys={['0']}
                defaultOpenKeys={["0"]}
                // defaultSelectedKeys={[`${this.state.roleGroupData[0].comRolesList[0].roleId}`]}
                // defaultSelectedKeys={[`${this.state.defaultSelectedItem}`]}
                // defaultSelectedKeys={[`407895940217700352`]}
                // defaultOpenKeys={{this.state.roleGroupdefault}}
                onClick={this.roleMenuClick.bind(this)}
                // openKeys={this.state.openKeys}
                // onOpenChange={this.onOpenChange}
                style={{ width: 213 }}
              >
                {this.renderCourse()}
              </Menu>
            </div>
          </div>
          <div className="department-demonstrate">
            <div className="demonstrate-head">
              <p className="title">
                <span className="current-role">
                  <Icon
                    type="user"
                    style={{
                      fontSize: 20,
                      color: "#909CA8",
                      marginRight: "6px"
                    }}
                  />
                  {this.state.caption}({this.state.personCount}人)
                </span>
                {this.state.roleGroupSequence === "" ? (
                  <Button
                    className="role-button"
                    style={{ marginLeft: "32px" }}
                    onClick={this.openUpdateRoleDrawer.bind(
                      this,
                      true,
                      this.state.pageParm.roleId
                    )}
                    disabled
                  >
                    编辑
                  </Button>
                ) : (
                  <Button
                    className="role-button"
                    style={{ marginLeft: "32px" }}
                    onClick={this.openUpdateRoleDrawer.bind(
                      this,
                      true,
                      this.state.pageParm.roleId
                    )}
                  >
                    编辑
                  </Button>
                )}
                <Button
                  className="role-button"
                  onClick={this.openRoleAllowDrawer.bind(
                    this,
                    true,
                    this.state.pageParm.roleId
                  )}
                >
                  权限设置
                </Button>
              </p>
            </div>
            {/* <div className="demonstrate-line"></div> */}
            <div className="subordinate-departments">
              <div className="division-button">
                <Button
                  type="primary"
                  icon="plus"
                  disabled={this.state.roleGroupSequence === ""}
                  onClick={() => {
                    this.setState({ chargePerVisible: true });
                  }}
                >
                  添加成员
                </Button>

                {this.state.roleGroupSequence === "" ? (
                  <Button
                    disabled
                    type="danger"
                    ghost
                    onClick={this.handleDeleteList}
                  >
                    批量移除
                  </Button>
                ) : (
                  <Button type="danger" ghost onClick={this.handleDeleteList}>
                    批量移除
                  </Button>
                )}
              </div>
              <div className="division-table">{this.renderColums()}</div>
            </div>
          </div>
        </div>
        {this.renderUserSelect()}
        {/* 删除模态框 */}
        <div>
          <Modal
            title="提示"
            visible={visible}
            onOk={this.handleOk}
            confirmLoading={confirmLoading}
            onCancel={this.handleCancel}
            okText="确认"
            cancelText="取消"
          >
            <p style={{ textAlign: "center", fontSize: "14px", color: "#333" }}>
              <i
                className="anticon anticon-exclamation-circle"
                style={{
                  color: "#faad14",
                  fontSize: "22px",
                  marginRight: "16px",
                  verticalAlign: "middle"
                }}
              />
              {ModalText}
            </p>
          </Modal>
        </div>
        {/* 批量离职删除模态框 */}
        <div>
          <Modal
            title="提示"
            visible={bulkDeparturesVisible}
            onOk={this.handleBulkDeparturesOk}
            confirmLoading={bulkDeparturesConfirmLoading}
            onCancel={this.handleBulkDeparturesCancel}
            okText="确认"
            cancelText="取消"
          >
            <p style={{ textAlign: "center", fontSize: "14px", color: "#333" }}>
              <i
                className="anticon anticon-exclamation-circle"
                style={{
                  color: "#faad14",
                  fontSize: "22px",
                  marginRight: "16px",
                  verticalAlign: "middle"
                }}
              />
              {BulkDeparturesModalText}
            </p>
          </Modal>
        </div>
        {/* 新增角色 */}
        <RoleAllow
          onChange={roleAllowOpen => {
            this.setState({ roleAllowOpen });
          }}
          visiable={this.state.roleAllowOpen}
          roleId={this.state.edit.roleId}
          caption={this.state.caption}
          refreshList={() => {
            this.getSearchRoleAndRoleGroupList();
          }}
          wedRoleSequence={this.updateRoleGroupSequence}
        />
        <UpdateRole
          onChange={updateRoleOpen => {
            this.setState({ updateRoleOpen });
          }}
          visiable={this.state.updateRoleOpen}
          roleId={this.state.edit.roleId}
          refreshList={() => {
            this.getSearchRoleAndRoleGroupList();
          }}
          wedRoleSequence={this.updateRoleGroupSequence}
        />
        <NewRole
          onChange={roleOpen => {
            this.setState({ roleOpen });
          }}
          visiable={this.state.roleOpen}
          refreshList={() => {
            this.getSearchRoleAndRoleGroupList();
          }}
          wedRoleSequence={this.updateRoleGroupSequence}
        />
        <NewRoleGroup
          onChange={roleGroupOpen => {
            this.setState({ roleGroupOpen });
          }}
          visiable={this.state.roleGroupOpen}
          refreshList={() => {
            this.getSearchRoleAndRoleGroupList();
          }}
          wedRoleSequence={this.updateRoleGroupSequence}
        />
        <UpdateRoleGroup
          onChange={updateroleGroupOpen => {
            this.setState({ updateroleGroupOpen });
          }}
          visiable={this.state.updateroleGroupOpen}
          roleGroupId={this.state.edit.roleGroupId}
          refreshList={() => {
            this.getSearchRoleAndRoleGroupList();
          }}
          wedRoleSequence={this.updateRoleGroupSequence}
        />
      </div>
    );
  }
}
